/**
 * @description orderModel Service
 */

const {
  orderModel
} = require('../db/index')
const Op = require('sequelize').Op

async function addData(params) {
  try {
    const result = await orderModel.create(params)
    const data = result.dataValues
    return data
  } catch (error) {
    console.log(error)
  }
}

async function updateData(
  params,
  id
) {
  // 拼接修改内容
  const updateObj = params

  // 拼接查询条件
  const whereOption = {}
  if (id) {
    whereOption.id = id
  }

  // 执行修改
  const result = await orderModel.update(updateObj, {
    where: whereOption
  })
  return result[0] > 0
}

async function deleteData(id) {
  const result = await orderModel.destroy({
    where: {
      id
    }
  })
  return result > 0
}

async function queryByNo(no) {
  const result = await orderModel.findAll({
    where: {
      no
    }
  })
  return {
    exsit: !!result.length
  }
}

async function queryAll(params) {
  console.log(params)
  const {
    page = 1,
    pageSize = 10,
    state,
    userId
  } = params
  if (page < 1) {
    page = 1
  }
  let whereOption = {}

  if (state) {
    whereOption.state = state
  }
  if (userId) {
    whereOption.userId = userId
  }
  console.log(whereOption)
  const result = await orderModel.findAll({
    limit: pageSize,
    offset: (page - 1) * pageSize,
    where: whereOption
  })
  console.log(result)
  const total = await orderModel.findAll({
    where: whereOption
  })
  return {
    page,
    pageSize,
    total: total.length || 0,
    data: result || []
  }
}

module.exports = {
  addData,
  updateData,
  deleteData,
  queryAll,
  queryByNo
}